//
//  CountdownTableViewCell.m
//  HaoHint
//
//  Created by winter on 16/5/23.
//  Copyright © 2016年 wd. All rights reserved.
//

#import "CountdownTableViewCell.h"
#import "LocalNotificationTool.h"

#define kEnterBackgroundDateKey @"enterBackgroundDate"

@interface CountdownTableViewCell ()
@property (weak, nonatomic) IBOutlet UILabel *eventTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeRingLabel;

@property (weak, nonatomic) IBOutlet UILabel *countdownLabel;

@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UIButton *startTimeButton;

@property (weak, nonatomic) IBOutlet UIView *editView;

@property (nonatomic, strong) NSTimer *timer;
// 倒计时时间
@property (nonatomic, assign) NSInteger second;
// 提前时间
@property (nonatomic, assign) NSInteger preRemindSecond;
@end

@implementation CountdownTableViewCell

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)setCountdownModel:(CountdownModel *)countdownModel
{
    _countdownModel = countdownModel;
    
    self.countdownLabel.text = countdownModel.countdownTime;
    self.eventTitleLabel.text = countdownModel.timeTitle;
    self.remindLabel.text = countdownModel.remindString;
    self.timeRingLabel.text = countdownModel.soundTitle;
    
    self.second = countdownModel.timeSecond;
    self.preRemindSecond = countdownModel.remindEarlyType * 60;
}

#pragma mark - NSNotificationCenter

- (void)applicationDidEnterBackground
{
    NSDate *date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:kEnterBackgroundDateKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)applicationWillEnterForeground
{
    NSDate *curDate = [NSDate date];
    NSDate *preDate = [[NSUserDefaults standardUserDefaults] objectForKey:kEnterBackgroundDateKey];
    
    NSTimeInterval timeInterVal = [curDate timeIntervalSinceDate:preDate];
    
    if (timeInterVal >= self.second) {
        [self cancelCountdown];
    }
    else {
        self.second -= timeInterVal;
    }
}

#pragma mark - buttonAction

- (IBAction)buttonAction:(UIButton *)sender
{
    if (100 == sender.tag) {
        // 取消
        [self cancelCountdown];
    }
    else if (101 == sender.tag) {
        // 暂停/继续
        sender.selected = !sender.isSelected;
        [self timerPause:sender.isSelected];
    }
    else {
        // 开始计时
        sender.hidden = YES;
        self.buttonView.hidden = NO;
        
        [self startTimeCount];
        
        self.countdownModel.countdowning = YES;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
}

- (void)cancelCountdown
{
    self.startTimeButton.hidden = NO;
    self.buttonView.hidden = YES;
    
    [self cancelTimer];
    
    self.countdownModel.countdowning = NO;
    self.selectionStyle = UITableViewCellSelectionStyleDefault;
}

#pragma mark - 通知

- (void)addLocalNotification
{
    LocalNotificationModel *model = [[LocalNotificationModel alloc] init];
//    model.alertBody = self.countdownModel.alertBody;//@"计时30分";
//    model.alertAction = self.countdownModel.timeTitle;//@"5分钟后结束";
    model.alertBody = self.countdownModel.timeTitle;//@"计时30分";
    model.seconds = self.second;
    model.preSeconds = self.preRemindSecond;
    model.soundName = self.countdownModel.soundName;
    model.preSoundName = self.countdownModel.preSoundName;
    model.localNotificationID = self.countdownModel.countdownID;
    
//    model.seconds = 10;
//    model.preSeconds = 5;
    
    if (model.seconds <= model.preSeconds) {
        model.preSeconds = 0;
    }
    
    [LocalNotificationTool scheduleLocalNotification:model];
}

- (void)removeLocalNotification
{
    [LocalNotificationTool cancelLocalNotification:self.countdownModel.countdownID];
}

#pragma mark - 计时

- (void)refreshCountdownLabel:(NSInteger)second
{
    NSInteger HValue = second / 3600;
    NSInteger MValue = (second / 60) % 60;
    NSInteger SValue = second % 60;
    
    NSString *time = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld",(long)HValue,(long)MValue,(long)SValue];
    
    self.countdownLabel.text = time;
    
    if (self.countdownModel.isPreRemind) {
        
        if (self.preRemindSecond >= second) {
            self.countdownModel.preRemind = NO;
        }
    }
    
    if ([time isEqualToString:@"00:00:00"]) {
        [self cancelTimer];
        self.startTimeButton.hidden = NO;
        self.buttonView.hidden = YES;
         NSLog(@"计时结束");
    }
}

- (void)timeIntervalChanged:(NSTimer *)timer
{
    self.second--;
    [self refreshCountdownLabel:self.second];
}

- (void)startTimeCount
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeIntervalChanged:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    // 添加通知
    [self addLocalNotification];
}

- (void)stopTimeCount
{
    [self.timer invalidate];
    self.timer = nil;
    
    // 移除通知
    [self removeLocalNotification];
}

- (void)cancelTimer
{
    [self stopTimeCount];
    
    self.second = self.countdownModel.timeSecond;
    [self refreshCountdownLabel:self.second];
}

- (void)timerPause:(BOOL)pause
{
    if (pause) {
        [self stopTimeCount];
    }
    else {
        [self startTimeCount];
    }
}
@end
